<template>
  <CommonPage>
    <MyTabs v-model="tabList.active" :options="tabList.tabs" />
    <MyTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="replayApi.list"
      :index="true"
      list-key="replay_list"
      :height="600"
      @on-reset="methods.handleTableReset"
    >
      <template #search>
        <MyTQI>
          <AsyncSelect
            v-model:value="queryItems.projectId"
            placeholder="选择项目"
            :options="methods.getProjectOptions"
            :init-remote="true"
            remote
          />
        </MyTQI>
        <MyTQI>
          <AsyncSelect
            v-model:value="queryItems.problemLevel"
            placeholder="选择定义等级"
            options="PROBLEM_LEVEL"
          />
        </MyTQI>
      </template>
      <template #action>
        <n-button v-permission="`replay_add`" type="primary" @click="handleAdd">添加</n-button>
      </template>
    </MyTable>
    <MyDrawer
      ref="$form"
      :model-form="model"
      :disabled="type === 'view'"
      :width="800"
      @submit="handleSubmit"
    >
      <div class="mb-10 text-16 font-bold">事故基本情况</div>
      <n-form-item
        label="选择项目"
        path="projectId"
        :rule="[{ required: true, message: '请选择项目!' }]"
      >
        <AsyncSelect
          v-if="isRender"
          v-model:value="model.projectId"
          :options="methods.getProjectOptions"
          :init-remote="true"
          remote
          :disabled="isFinal"
        />
      </n-form-item>
      <n-form-item
        label="问题描述"
        path="problemDescription"
        :rule="[{ required: true, message: '请输入问题描述!' }]"
      >
        <n-input
          v-model:value="model.problemDescription"
          type="textarea"
          maxlength="300"
          show-count
          clearable
          :autosize="{
            minRows: 3,
          }"
          :disabled="isFinal"
        />
      </n-form-item>
      <n-form-item label="月份" path="monthTime">
        <n-date-picker
          v-model:formatted-value="model.monthTime"
          type="month"
          clearable
          :disabled="isFinal"
        />
      </n-form-item>
      <n-form-item label="问题分类" path="problemType">
        <AsyncSelect v-model:value="model.problemType" options="PROBLEM_TYPE" :disabled="isFinal" />
      </n-form-item>
      <n-form-item label="责任人" path="personInChargeName">
        <AsyncSelect
          v-model:value="model.personInChargeName"
          :options="methods.getLeader"
          :disabled="isFinal"
          @update:value="(_, val) => methods.handleSelectLeader(val)"
        />
      </n-form-item>
      <n-form-item label="所属组" path="fsGroupType">
        <AsyncSelect
          v-model:value="model.fsGroupType"
          value-key="dept_id"
          label-key="name"
          :options="() => taskProjectApi.deptAllList().then((res) => res.data)"
          :disabled="true"
        />
      </n-form-item>
      <n-form-item label="时间" path="occurrenceTime">
        <n-date-picker
          v-model:formatted-value="model.occurrenceTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          :time-picker-props="{ format: 'HH:mm' }"
          clearable
          :disabled="isFinal"
        />
      </n-form-item>
      <n-form-item label="备注" path="remark">
        <n-input
          v-model:value="model.remark"
          type="textarea"
          maxlength="300"
          show-count
          clearable
          :autosize="{
            minRows: 3,
          }"
          :disabled="isFinal"
        />
      </n-form-item>
      <n-form-item label="附件" path="refFileDtoList">
        <FileUpload v-model="model.refFileDtoList" :disabled="isFinal" />
      </n-form-item>
      <div class="mb-10 text-16 font-bold">事故初步定级</div>
      <n-form-item label="组长初步定级" path="problemLevel">
        <AsyncSelect
          v-model:value="model.problemLevel"
          options="PROBLEM_LEVEL"
          :disabled="isFinal"
        />
      </n-form-item>
      <n-form-item label="处理方式" path="handleMethod">
        <n-input
          v-model:value="model.handleMethod"
          type="textarea"
          maxlength="300"
          show-count
          clearable
          :autosize="{
            minRows: 3,
          }"
          :disabled="isFinal"
        />
      </n-form-item>
      <n-form-item label="处理启动" path="handleYearStart">
        <n-space>
          <n-date-picker
            v-model:formatted-value="model.handleYearStart"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            clearable
            :disabled="isFinal"
          />
          <n-time-picker
            v-model:formatted-value="model.handleHourStart"
            value-format="HH:mm:ss"
            format="HH:mm"
            placeholder="选择时间"
            clearable
            :disabled="!model.handleYearStart || type === 'view' || isFinal"
          />
        </n-space>
      </n-form-item>
      <n-form-item
        label="处理结束"
        path="handleYearEnd"
        :rule="[{ validator: methods.validatorDate }]"
      >
        <n-space>
          <n-date-picker
            v-model:formatted-value="model.handleYearEnd"
            placeholder="选择日期"
            clearable
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :disabled="isFinal"
          />
          <n-time-picker
            v-model:formatted-value="model.handleHourEnd"
            placeholder="选择时间"
            clearable
            value-format="HH:mm:ss"
            format="HH:mm"
            :disabled="!model.handleYearEnd || type === 'view' || isFinal"
          />
        </n-space>
      </n-form-item>
      <div class="mb-10 text-16 font-bold">事故最终定级</div>
      <n-form-item label="最终定级" path="adjustLevel">
        <AsyncSelect
          v-model:value="model.adjustLevel"
          options="ADJUST_LEVEL"
          :disabled="!hasPermission('replay_final') || type === 'view'"
        />
      </n-form-item>
      <n-form-item label="绩效扣罚比例" path="kpiReduce">
        <n-input-number
          v-model:value="model.kpiReduce"
          :min="0"
          :max="100"
          clearable
          :disabled="!hasPermission('replay_final') || type === 'view'"
        >
          <template #suffix>%</template>
        </n-input-number>
      </n-form-item>
      <n-form-item label="调整定级原因" path="adjustLevelReason">
        <n-input
          v-model:value="model.adjustLevelReason"
          type="textarea"
          maxlength="300"
          show-count
          clearable
          :disabled="!hasPermission('replay_final') || type === 'view'"
          :autosize="{
            minRows: 3,
          }"
        />
      </n-form-item>
    </MyDrawer>
  </CommonPage>
</template>

<script setup lang="jsx">
import dayjs from 'dayjs'
import * as replayApi from '@/api/replay'
import * as projectApi from '@/api/project'
import * as taskProjectApi from '@/api/taskProject'
import { useCrudPro } from '@/hooks/useCrudPro'
import { useUserStore, usePermissionStore } from '@/store'
defineOptions({ name: 'ReplayIndex' })
onMounted(() => {
  taskProjectApi.deptList().then((res) => {
    tabList.tabs = res.data.map((v) => ({
      label: v.name,
      value: v.dept_id,
    }))
    tabList.tabs.unshift({ label: '全部', value: 'all' })
  })
})
const userStore = useUserStore()
const { hasPermission } = usePermissionStore()
const tabList = reactive({
  tabs: [],
  active: 'all',
})
const methods = reactive({
  getProjectOptions(searchVal, id) {
    return projectApi.listAll({ searchVal, id }).then((res) =>
      res.data.map((item) => ({
        label: `${item.projectName} V.${item.projectVersion || 0}.${item.projectVersionMinor || 0}`,
        value: item.id,
      }))
    )
  },
  getLeader() {
    return replayApi.getLeaderList().then((res) => {
      return res.data.map((v) => ({ label: v.name, value: v.name, deptId: v.deptId }))
    })
  },
  handleTableReset() {
    tabList.active = 'all'
  },
  handleSelectLeader(v) {
    model.value.fsGroupType = v?.deptId || null
  },
  validatorDate(_, __, callback) {
    const { handleYearStart, handleHourStart, handleYearEnd, handleHourEnd } = model.value
    if (handleYearStart && handleYearEnd) {
      const start = `${handleYearStart} ${handleHourStart || '00:00:00'}`
      const end = `${handleYearEnd} ${handleHourEnd || '00:00:00'}`
      if (dayjs(start).isAfter(dayjs(end))) {
        callback(new Error('处理结束时间要大于处理启动时间!'))
      } else {
        callback()
      }
    } else {
      callback()
    }
  },
})
const queryItems = ref({})
watch(
  () => tabList.active,
  (v) => {
    if (v !== 'all') {
      queryItems.value.fsGroupType = v
      $table?.value?.handleSearch()
    } else {
      queryItems.value.fsGroupType = null
      $table?.value?.handleSearch()
    }
  }
)
const columns = [
  {
    title: '问题描述',
    key: 'problemDescription',
  },
  {
    title: '项目名称',
    key: 'projectName',
    render: (row) =>
      `${row.projectName} V.${row.projectVersion || 0}.${row.projectVersionMinor || 0}`,
  },
  {
    title: '组长初步定级',
    key: 'problemLevelName',
  },
  {
    title: '处理方式',
    key: 'handleMethod',
  },
  {
    title: '处理启动',
    key: 'handleYearStart',
    render(row) {
      return $format(
        row.handleYearStart && `${row.handleYearStart} ${row.handleHourStart || '00:00:00'}`
      )
    },
  },
  {
    title: '处理结束',
    key: 'handleYearEnd',
    render(row) {
      return $format(row.handleYearEnd && `${row.handleYearEnd} ${row.handleHourEnd || '00:00:00'}`)
    },
  },
  {
    title: '责任人',
    key: 'personInChargeName',
  },
  {
    title: '问题分类',
    key: 'problemTypeName',
  },
  {
    title: '时间',
    key: 'createTime',
    render: ({ createTime }) => $format(createTime),
  },
  {
    title: '操作',
    key: 'actions',
    width: 220,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <n-button v-permission="replay_view" text onClick={() => handleView({ id: row.id })}>
            查看
          </n-button>
          <n-button
            v-permission="replay_update"
            text
            onClick={() => handleEdit({ id: row.id })}
            disabled={!(row.createUser === userStore.userId || hasPermission('replay_final'))}
          >
            修改
          </n-button>
          <n-button
            v-permission="replay_delete"
            text
            onClick={() =>
              handleDelete(
                { id: row.id },
                {
                  title: '删除复盘记录',
                  content: `请确定是否删除复盘记录：${row.problemDescription}`,
                }
              )
            }
            disabled={!(row.createUser === userStore.userId || userStore.isHigh)}
          >
            删除
          </n-button>
        </n-flex>
      )
    },
  },
]
const isFinal = ref(false)
const {
  type,
  isRender,
  model,
  $form,
  $table,
  handleAdd,
  handleSubmit,
  handleView,
  handleDelete,
  handleEdit,
} = useCrudPro({
  name: '复盘记录',
  initForm: {
    id: null,
    projectId: null,
    problemDescription: null,
    problemLevel: null,
    adjustLevel: null,
    handleMethod: null,
    handleYearStart: null,
    handleHourStart: null,
    handleYearEnd: null,
    handleHourEnd: null,
    personInChargeName: null,
    fsGroupType: null,
    problemType: null,
    remark: null,
    refFileDtoList: [],
    adjustLevelReason: null,
    kpiReduce: null,
    occurrenceTime: null,
    monthTime: null,
  },
  apis: {
    add: replayApi.add,
    edit: replayApi.edit,
    del: replayApi.del,
    info: ({ id }) =>
      replayApi.info({ id }).then((res) => {
        isFinal.value = res.data.adjustLevel && !userStore.isHigh
        return res.data
      }),
  },
})
</script>
